package blockchain.dao.levelDB;

import blockchain.dao.DAOService;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBFactory;
import org.iq80.leveldb.DBIterator;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Iq80DBFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.util.Strings;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @Author: 李浩然
 * @Date: 2021/3/7 11:43 下午
 */
public class LeveldbDAO implements DAOService {
    //日志
    private Logger logger = LoggerFactory.getLogger(LeveldbDAO.class);

    private DB db;

    @PostConstruct
    public void init() {
        try {
            DBFactory factory = new Iq80DBFactory();
            Options options = new Options();
            options.createIfMissing(true);
//            String path = "./leveldb";
            String path = "/Users/lihaoran/Desktop/project/SCASverify/fabric-nodejs/history_test/historyLeveldb";
            db = factory.open(new File(path), options);
//            db.put("test".getBytes(), "test".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入数据
     *
     * @param key
     * @param value
     */
    public void put(String key, String value) {
        if (Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(value)) {
            return;
        }
        db.put(Iq80DBFactory.bytes(key), Iq80DBFactory.bytes(value));
    }

    /**
     * 获取数据
     *
     * @param key
     * @return
     */
    public String get(String key) {
        if (Strings.isNullOrEmpty(key)) {
            System.out.println("查找失败，查找值=" + key);
            return null;
        }
        byte[] valueBytes = db.get(Iq80DBFactory.bytes(key));
        return Iq80DBFactory.asString(valueBytes);
    }

    /**
     * 删除数据
     *
     * @param key
     */
    public void delete(String key) {
        if (Strings.isNullOrEmpty(key)) {
            return;
        }
        db.delete(Iq80DBFactory.bytes(key));
    }

    /**
     * 遍历所有数据
     */
    public void traverseAllDatas() {
        DBIterator iterator = db.iterator();
        while (iterator.hasNext()) {
            Map.Entry<byte[], byte[]> next = iterator.next();
            String key = Iq80DBFactory.asString(next.getKey());
            String value = Iq80DBFactory.asString(next.getValue());
            logger.info("遍历所有数据,key=" + key + "        value=" + value);
        }
    }

    public static void main(String[] args) {
        LeveldbDAO leveldbDAO = new LeveldbDAO();
        leveldbDAO.init();
        leveldbDAO.traverseAllDatas();
    }
}
